import { MemoryManager } from "GameLoop/DecisionMaking/MemoryManager";
import { ABaseEntity } from "../BaseEntity";
import { TaskHelper } from "utils/task/TaskHelper";
import { getRoleConfig } from "utils/constants/bodyconstant";
export enum ETeamState 
{
    init=0,     // 等待初始化
    Full=1,     // 满员
    Absence=2,  // 减员
    Dead=3      // 小队已经狗带
}
/**
 * 小队设置一个默认ttl。ttl到0就删除team.防止因script中断导致的孵化bug.
 * 小队存在爬之后。以爬的ttl为小队的ttl
 */ 
export  abstract class ATeamEntity<T extends ITeamMemory=ITeamMemory ,I extends ITeamInitializer=ITeamInitializer >  extends ABaseEntity<T,I> 
{
     
    public get region(): string
    {
        return  this._initializer.roomName
    }
        
    public get room():Required< Room>
    {
        return Game.rooms[this.region] as Required< Room>;
    }
    /**
     * 投递孵化爬的任务
     */
    abstract postSpawn(priority?:number):void
    public   getNodeMemory (): T {
        const regionCache = MemoryManager.getMemory<IMemoryCache>(this.region);
        if(!regionCache.Nodes ||!regionCache.Nodes[this.key])
        {
            throw new Error(`${this.GUID}->${this.entityType()} 的内存未初始化`)
        }
        return regionCache.Nodes[this.key]
    }
    
   
    // 初始化属性。小队应该没有吧、
    public initAttributes(): void {
        this.initNodeMemory();
       
    }
    abstract updateMemory(): void;
    abstract get teamTimeTickLive():number

    // 初始化内存
    protected initNodeMemory()
    {
        const regionCache = MemoryManager.getMemory<IMemoryCache>(this.region);
        if(!regionCache.Nodes)
        {
            regionCache.Nodes={};
             
        }
        if(!regionCache.Nodes[this.key])
        {
            regionCache.Nodes[this.key]={};
        }
        const memory  = this.getNodeMemory();
        if(!memory.creeps)
        {
            memory.creeps={} as any;
        }
        if(!memory.type)
        {
            memory.type = this.entityType();
        }
        if(!memory.region)
        {
            memory.region =  this.region;
        }
    }
    public addCreep(creep:Creep[])
    {
        const memory = this.getNodeMemory();
        for(const c of creep)
        {
            if(memory.creeps[c.memory.Role])
            {
                if(memory.creeps[c.memory.Role].includes(c.name))
                {
                    global.Log.Warning(`${JSON.stringify(memory.creeps[c.memory.Role])} 重复绑定 :${c.name}`);
                    continue;
                }
                memory.creeps[c.memory.Role].push(c.name);
            }
            else
            {
                memory.creeps[c.memory.Role]=[c.name];
            }
        }
        return true
    }
    /**
     * 获取team的爬
    */
    get creeps():Creep[]
    {
         
        return  (_.flatten(Object.values(this.getNodeMemory().creeps)).map(e=>Game.creeps[e])).filter(e=>e);
 
    }
   
    get groupCreeps()
    {
        const validcreeps:Record<RoleName,Creep[]> ={} as any;
        const memory = this.getNodeMemory();
        for(let role in memory.creeps)
        {
            const creeps:Creep[]=[];
            for(let i=0;i< memory.creeps[role as RoleName].length;)
            {
                const name = memory.creeps[role as RoleName][i];
                if(Game.creeps[name])
                {
                    creeps.push(Game.creeps[name]);
                    i++
                }
                else
                {
                    memory.creeps[role as RoleName].splice(i,1);
                }
            }
            validcreeps[role as RoleName] = creeps
        }
        return validcreeps
    }
    get isTeamMoveReady():boolean
    {
        return  this.getNodeMemory().teamState != ETeamState.init
        // return true;
    }
    // public log(type:LogType,...arg:any[]):void
    // {
    //     super.log(type,`${this.creeps.map(e=>e.name)}`,...arg)
    // }
     /**
     * 投递孵化爬的任务
     */
     protected postSpawnImpl(existcreeps:Record<RoleName,Creep[]>,priority:number)  
     {
         const room = this.room;
          
         const spawnentity = this.getEntity("SpawnEntity");
         const memory = this.getNodeMemory();
         const spawnRecord:Record<RoleName,number>={} as any;
         const roleRecord:Record<RoleName,IBodyConfig>={} as any;
         let spawn_num=0;
         const validcreeps:Record<RoleName,Creep[]> =existcreeps;
         for(const e of memory.required)
         {
             const role =  e[0].Role;
             const existnum = validcreeps[role]?validcreeps[role].length:0;
             // 本任务已经达标了
             const spawnNum = spawnentity.getSpawnCountByRole(role,this.GUID()); 
             spawn_num+= spawnNum;
             const tasklimit = e[1]- (spawnNum+existnum);
             if(tasklimit<=0)
             {
                 // 正在孵化的。已经有的。达到了需求
                 continue;
             }
             spawnRecord[role] = tasklimit;
             roleRecord[role] = e[0];
         }
         const spawntask = TaskHelper.getSpawnTask(this.GUID(),undefined, priority);
         for(let k in spawnRecord)
         {
            TaskHelper.pushSpawnInfo(spawntask,roleRecord[k as RoleName],spawnRecord[k as RoleName]);
         }
         
         if(spawntask.data.spawn_info.length>0)
         {
             spawnentity.addTask(spawntask);
             return spawntask;
         }
         return undefined
     }

     public onDestory(): boolean 
     {
         
        const creeps = this.getNodeMemory().creeps;
        for(let k in creeps)
        {
        for(const e of creeps[k as RoleName])
        {
            if(Game.creeps[e])
            {
                Game.creeps[e].memory.teamid == undefined;
                Game.creeps[e].memory.taskid == undefined;
            }
        }
        }
        this.getNodeMemory().creeps={} as any;
        super.onDestory();
         return true;
     }
}